package cn.ictgu.parse.crawler;

import cn.ictgu.config.OtherParseConfig;
import cn.ictgu.dto.VideoInfo;
import cn.ictgu.dao.model.Juji;
import cn.ictgu.parse.VideoParse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.nodes.Document;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 搜狐视频
 * Created by Silence on 2017/1/7.
 */
public class Sohu extends VideoParse {

  private static final String SOHU = "搜狐视频";

  private static final String INFO_API = "http://m.tv.sohu.com/phone_playinfo?vid=";
  private static final String SOUHU_VIDEOS = "http://pl.hd.sohu.com/videolist?playlistid=";

  @Override
  public VideoInfo parseVideoFromUrl(String videoUrl) {
    VideoInfo videoInfo =  createVideoInfoWithCopyRight(SOHU, videoUrl, OtherParseConfig.OFFICIAL_NAME, OtherParseConfig.OFFICIAL_WEBSITE);
    String title = crawlerTitle(videoUrl);
    videoInfo.setTitle(title);
    String playUrl = commenParse(videoUrl);
    videoInfo.setPlayUrl(playUrl);
    videoInfo.setType("NORMAL");
    return videoInfo;
  }

  @Override
  public List<Juji> parseJujiFromUrl(String videoUrl) {
    List<Juji> jujis = new ArrayList<>();
    Document document = getDocument(videoUrl);
    Matcher matcher = Pattern.compile("var playlistId=\"(.*?)\"").matcher(document.html());
    if (matcher.find()) {
      String vid = matcher.group(1);
      String videosAPI = SOUHU_VIDEOS + vid;
      String data = getDocument(videosAPI).body().text();
      JSONObject jsonObject = JSONObject.parseObject(data);
      JSONArray array = jsonObject.getJSONArray("videos");
      if (array.size()>0){
        for (int i = array.size() - 1; i >= 0; i--) {
          JSONObject object = array.getJSONObject(i);
          Juji juji = new Juji();
          Integer index = object.getInteger("order");
          if (index < 10) {
            juji.setIndex("0" + index);
          } else {
            juji.setIndex("" + index);
          }
          juji.setValue(object.getString("pageUrl"));
          jujis.add(juji);
        }
      }
    }
    return jujis;
  }

  private String getVid(String videoUrl){
    String vid = "";
    Matcher matcher = Pattern.compile("v([0-9]+)\\.shtml").matcher(videoUrl);
    if (matcher.find()){
      vid = matcher.group(1);
    }else {
      Document document = getDocument(videoUrl);
      matcher = Pattern.compile("vid(=|:)\"?([0-9]+)").matcher(document.html());
      if (matcher.find()) {
        vid = matcher.group(2);
      }
    }
    return vid;
  }

  private String crawlerTitle(String videoUrl){
    String vid = this.getVid(videoUrl);
    String api = INFO_API + vid;
    Document document = getDocument(api);
    JSONObject json = JSONObject.parseObject(document.body().text());
    JSONObject data = json.getJSONObject("data");
    return data.getString("video_name");
  }
}
